package net;

import java.lang.reflect.InvocationTargetException;

import log.L;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class HandleFrameData extends  SimpleChannelUpstreamHandler {
    
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
    	L.debug(e.getChannel().getRemoteAddress()  + " close");
    }
    
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
    	L.debug(e.getChannel().getRemoteAddress()  + " connect");
    }
    
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
    	L.debug(e.getChannel().getRemoteAddress()  + " disconnect");
    }
    
    
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {    	
    	ChannelBuffer data = (ChannelBuffer)e.getMessage();
    	int version = data.readInt();
		String msg = Protocol.readString(data);
		Client client = new Client();
		client.channel = e.getChannel();
		client.version = version;
		if (!MessageRouter.route(msg, client)) {
			client.channel.close();
		}
    }
    
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		L.error(e.toString());
		Throwable cause = e.getCause();
		StackTraceElement[] trace;
		if (cause instanceof OutOfMemoryError) {
//			Config.SERVER_STATE = 1;
		}
		if (cause instanceof InvocationTargetException) {
			InvocationTargetException ite = (InvocationTargetException)cause;
			L.error(ite.getTargetException().toString());
			trace = ite.getTargetException().getStackTrace();
		} else {
			trace = cause.getStackTrace();
		}
		
		for (StackTraceElement st: trace) {
			L.error(st.toString());
		}
		ctx.getChannel().close();
	}
}
